<template>
  <div id="goods_detail" style="padding:30px;">
    <el-col :span="80" :offset="0">
      <el-card class="box-card is-always-shadow" style="padding-top:10px;">
        <h3>商品信息</h3>
        <div class="card_body" style="padding-left:30px;">
          <el-form ref="form" :model="edit" :rules="productFormRules" label-width="80px" class="el-form-item--medium">
            <el-form-item label="商品编号" prop="goodsSn">
              <el-input ref="goodsName" v-model="edit.goodsSn" :disabled="true" class="el-input--medium" />
            </el-form-item>
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="edit.name" class="el-input--medium" />
            </el-form-item>
            <el-form-item label="专柜价格" prop="counterPrice">
              <el-input v-model="edit.counterPrice" class="el-input--medium">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
            <el-form-item label="当前价格" prop="retailPrice">
              <el-input v-model="edit.retailPrice" class="el-input--medium">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
            <el-form-item label="佣金设置">
              <template>
                <el-radio-group v-model="edit.brokerageType">
                  <el-radio :label="0" class="el-radio--medium">无佣金</el-radio>
                  <el-radio :label="1" class="el-radio--medium">自定义</el-radio>
                </el-radio-group>

              </template>
            </el-form-item>
            <el-form-item label="是否新品">
              <template>
                <el-radio-group v-model="edit.isNew">
                  <el-radio :label="1" class="el-radio--medium">新品</el-radio>
                  <el-radio :label="0" class="el-radio--medium">非新品</el-radio>
                </el-radio-group>
              </template>
            </el-form-item>
            <el-form-item label="是否热卖">
              <template>
                <el-radio-group v-model="edit.isHot">
                  <el-radio :label="0" class="el-radio--medium">普通</el-radio>
                  <el-radio :label="1" class="el-radio--medium">热卖</el-radio>
                </el-radio-group>
              </template>
            </el-form-item>
            <el-form-item label="是否热卖">
              <template>
                <el-radio-group v-model="edit.isOnSale">
                  <el-radio :label="1" class="el-radio--medium">在售</el-radio>
                  <el-radio :label="0" class="el-radio--medium">未售</el-radio>
                </el-radio-group>
              </template>
            </el-form-item>
            <el-form-item label="商品图片">
              <el-upload
                class="avatar-uploader"
                :action="doUpload"
                :headers="{ token: token }"
                :show-file-list="false"
                :auto-upload="true"
                list-type="picture-card"
                accept="image/jpeg,image/gif,image/png,image/bmp"
                :on-success="onSuccessImgUrl"
              >
                <label class="el-upload-list__item-status-label">
                  <i class="el-icon-upload-success el-icon-check" />
                </label>
                <img v-if="edit.picUrl" :src="edit.picUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>

            </el-form-item>
            <el-form-item label="宣传画廊">
              <el-upload
                ref="upload"
                :action="doUpload"
                class="avatar-uploader"
                :headers="{ token: token }"
                list-type="picture-card"
                :auto-upload="true"
                :limit="7"
                :file-list="fileList"
                accept="image/jpeg,image/gif,image/png,image/bmp"
                :on-success="onSuccess"
                :on-error="uploadError"
              >
                <i slot="default" class="el-icon-plus" />
                <div slot="file" slot-scope="{ file }">
                  <label class="el-upload-list__item-status-label">
                    <i class="el-icon-upload-success el-icon-check" />
                  </label>
                  <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                  <span class="el-upload-list__item-actions">
                    <span
                      class="el-upload-list__item-preview"
                      @click="handlePictureCardPreview(file)"
                    >
                      <i class="el-icon-zoom-in" />
                    </span>
                    <span
                      v-if="!disabled"
                      class="el-upload-list__item-delete"
                      @click="handleRemove(file)"
                    >
                      <i class="el-icon-delete" />
                    </span>
                  </span>
                </div>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-form-item>
            <el-form-item label="商品单位" prop="unit">
              <el-input v-model="edit.unit" class="el-input--medium" />
            </el-form-item>
            <el-form-item label="关键字">
              <el-tag
                v-for="tag in keywords"
                :key="tag"
                closable
                :disable-transitions="false"
                style="margin-left: 10px;"
                @close="handleClose(tag)"
              >
                {{ tag }}
              </el-tag>
              <el-input
                v-if="inputVisible"
                ref="saveTagInput"
                v-model="inputValue"
                class="input-new-tag"
                size="small"
                @keyup.enter.native="handleInputConfirm"
                @blur="handleInputConfirm"
              />
              <el-button type="primary" class="el-input--medium" size="small" style="margin-left: 10px;" @click="showInput">增加</el-button>

            </el-form-item>
            <el-form-item label="所属类目">
              <el-cascader
                ref="cascaderHandle"
                :key="refresh"
                v-model="value"
                :options="categoryList"
                :props="{ expandTrigger: 'hover' }"
                clearable
                :multiple="false"
              />
            </el-form-item>

            <el-form-item label="商品简介">
              <el-input
                v-model="edit.brief"
                type="textarea"
                :rows="2"
                placeholder="请输入内容"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="商品详细介绍">
              <quill-editor
                ref="myTextEditor"
                v-model="edit.detail"
                :options="editorOption"
                style="height: 250px; margin-bottom: 10px"
              />
            </el-form-item>

          </el-form>

        </div>

      </el-card>
    </el-col>
    <el-col style="padding-top:15px;">
      <el-card class="box-card is-always-shadow">

        <h3>商品规格</h3>
        <template>
          <el-button :plain="true" type="primary" class="el-button--medium" @click="addSpecificationdialog">添加</el-button>
          <el-table
            :data="specificationTableData"
            style="width: 100%"
            :row-style="{height:'20px'}"
            :cell-style="{padding:'0px'}"
          >
            <el-table-column
              prop="specification"
              label="规格名称"
              width="380"
            />
            <el-table-column
              prop="value"
              label="规格值"
              width="380"
            >
              <template slot-scope="scope">
                <el-tag>{{ scope.row.value }}</el-tag>
              </template></el-table-column>
            <el-table-column
              prop="picUrl"
              label="规格图片"
              width="450"
              height="10"
            >
              <template slot-scope="scope">
                <el-image v-if="scope.row.picUrl" :src="scope.row.picUrl" style="width: 30%;" :style="{height:'60px'}">
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline" />
                  </div>
                </el-image>
              </template>
            </el-table-column>
            <el-table-column
              prop="address"
              label="操作"
              width="380"
            >
              <template slot-scope="scope">
                <el-button type="danger" class="el-button--medium" @click="removeSpecification(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-card>
    </el-col>

    <!-- 商品规格弹框-->
    <el-dialog title="添加商品规格" :visible.sync="specificationdialogFormVisible" :before-close="specificationdialogClose">
      <el-form ref="specification" :model="specification" :rules="specificationAddRules">
        <el-form-item label="规格名称" :label-width="formLabelWidth" prop="specification">
          <el-input v-model="specification.specification" autocomplete="off" class="el-input--medium" maxlength="10" style="width:50%;" />
        </el-form-item>
        <el-form-item label="规格值" :label-width="formLabelWidth" prop="value">
          <el-input v-model="specification.value" autocomplete="off" class="el-input--medium" maxlength="10" style="width:50%;" />
        </el-form-item>

        <el-form-item label="规格图片" :label-width="formLabelWidth" prop="picUrl">
          <el-upload
            ref="specificationUpload"
            class="avatar-uploader"
            :action="doUpload"
            :headers="{ token: token }"
            :auto-upload="false"
            :limit="1"
            list-type="picture-card"
            accept="image/jpeg,image/gif,image/png,image/bmp"
            :on-success="onSuccessSpecificationImg"
            :before-upload="checkSpecificationFile"
          >
            <label class="el-upload-list__item-status-label">
              <i class="el-icon-upload-success el-icon-check" />
            </label>
            <img v-if="specification.picUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>

        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="el-button--medium" @click="specificationdialogClose()">取 消</el-button>
        <el-button type="primary" class="el-button--medium" :loading="specificationLoading" @click="specificationdialogSubmit('specification')">确 定</el-button>
      </div>
    </el-dialog>

    <el-card class="box-card is-always-shadow">

      <h3>商品库存</h3>
      <template>
        <el-table
          :data="productListTableData"
          style="width: 100%"
          :row-style="{height:'20px'}"
          :cell-style="{padding:'0px'}"
          stripe
        >
          <el-table-column
            prop="specifications"
            label="货品规格"
            width="280"
          >
            <template slot-scope="scope">
              <p>{{ scope.row.specifications | specificationsfilters }}</p>
            </template>
          </el-table-column>
          <el-table-column
            prop="price"
            label="货品售价/元"
            width="240"
          >
            <template slot-scope="scope">
              <p>{{ scope.row.price | amountfilters }}</p>
            </template>
          </el-table-column>
          <el-table-column
            prop="number"
            label="货品数量"
            width="240"
          />
          <el-table-column
            prop="url"
            label="货品图片"
            width="450"
            height="10"
          >
            <template slot-scope="scope">
              <el-image v-if="scope.row.url" :src="scope.row.url" style="width: 30%;" :style="{height:'60px'}">
                <div slot="placeholder" class="image-slot">
                  加载中<span class="dot">...</span>
                </div>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column
            prop="address"
            label="操作"
            width="380"
          >
            <template slot-scope="scope">
              <el-button type="primary" class="el-button--medium" @click="specificationsdialogShow(scope.row)">设置</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-card>
    <el-card class="box-card is-always-shadow">
      <h3>商品参数</h3>
      <template>
        <el-button :plain="true" type="primary" class="el-button--medium" @click="handleAttributeShow">添加</el-button>
        <el-table
          :data="attributeListTableData"
          style="width: 100%"
          :row-style="{height:'20px'}"
          :cell-style="{padding:'0px'}"
          stripe
        >
          <el-table-column
            prop="attribute"
            label="参数名称"
            width="480"
          >
            <template slot-scope="scope">
              <p>{{ scope.row.attribute | specificationsfilters }}</p>
            </template>
          </el-table-column>
          <el-table-column
            prop="value"
            label="参数值"
            width="740"
          />
          <el-table-column
            prop="address"
            label="操作"
            width="330"
          >
            <template slot-scope="scope">
              <el-button type="danger" class="el-button--medium" @click="removeAttribute(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-card>

    <!-- 商品库存设置弹框-->
    <el-dialog title="商品库存设置" :visible.sync="specificationsdialogFormVisible" :before-close="specificationsdialogClose">
      <el-form ref="specificationsEdit" :model="editSpecifications" :rules="specificationsEditRules">
        <el-form-item label="货品规格" :label-width="formLabelWidth" prop="specifications">
          <el-input v-model="editSpecifications.specifications" autocomplete="off" class="el-input--medium" maxlength="10" style="width:50%;" />
        </el-form-item>
        <el-form-item label="货品售价/元" :label-width="formLabelWidth" prop="price">
          <el-input v-model="editSpecifications.price" autocomplete="off" class="el-input--medium" maxlength="10" style="width:50%;" />
        </el-form-item>
        <el-form-item label="货品数量" :label-width="formLabelWidth" prop="number">
          <el-input v-model="editSpecifications.number" type="number" autocomplete="off" class="el-input--medium" maxlength="10" style="width:50%;" />
        </el-form-item>
        <el-form-item label="货品图片" :label-width="formLabelWidth" prop="url">
          <el-upload
            ref="editSpecificationsUpload"
            class="avatar-uploader"
            :action="doUpload"
            :headers="{ token: token }"
            :auto-upload="true"
            :limit="1"
            list-type="picture-card"
            accept="image/jpeg,image/gif,image/png,image/bmp"
            :on-success="editSpecificationsImgSuccess"
            :before-upload="checkSpecificationFile"
          >
            <label class="el-upload-list__item-status-label">
              <i class="el-icon-upload-success el-icon-check" />
            </label>
            <img v-if="editSpecifications.url" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>

        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="el-button--medium" @click="specificationsdialogClose()">取 消</el-button>
        <el-button type="primary" class="el-button--medium" :loading="specificationLoading" @click="specificationsdialogSubmit('specificationsEdit')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 商品参数弹框-->
    <el-dialog title="添加商品参数" :visible.sync="attributedialogFormVisible" :before-close="attributedialogClose">
      <el-form ref="attribute" :model="attribute" :rules="attributeAddRules">
        <el-form-item label="参数名称" :label-width="formLabelWidth" prop="attribute">
          <el-input v-model="attribute.attribute" autocomplete="off" class="el-input--medium" maxlength="10" style="width:50%;" />
        </el-form-item>
        <el-form-item label="参数值" :label-width="formLabelWidth" prop="value">
          <el-input v-model="attribute.value" autocomplete="off" class="el-input--medium" maxlength="10" style="width:50%;" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="el-button--medium" @click="attributedialogClose()">取 消</el-button>
        <el-button type="primary" class="el-button--medium" :loading="specificationLoading" @click="attributedialogSubmit('attribute')">确 定</el-button>
      </div>
    </el-dialog>

    <div style="margin-top:15px;" class="op-container">
      <el-row>
        <el-button class="el-button--medium" @click="oncancle()">取消</el-button>
        <el-button type="primary" :loading="loading" class="el-button--medium" @click="pruductSubmit('form')">更新商品</el-button>
      </el-row>
    </div>
  </div>
</template>

<script>
import { queryShopGoodsByid, updateProduct } from '@/api/goods/index'
import { mapGetters } from 'vuex'
import { queryShopCategoryList } from '@/api/shop/shopcategory'
import quillConfig from '@/plugins/VueQuillEditor'
export default {
  filters: {
    specificationsfilters(val) {
      if (val === null) {
        return null
      }
      return val.toString().replace('[', '').replace(']', '').replace('"', '').replace('"', '')
    },
    amountfilters(val) {
      return (val / 100).toFixed(2)
    }
  },
  data() {
    return {
      loading: false,
      doUpload: process.env.VUE_APP_BASE_API + '/qiniuConfig/upload',
      goodId: null,
      edit: {
        id: null,
        goodsSn: null,
        name: null,
        counterPrice: null,
        retailPrice: null,
        brokerageType: null,
        isNew: null,
        isHot: null,
        isOnSale: null,
        picUrl: null,
        unit: null,
        keywords: null,
        brief: null
      },
      specification: {
        specification: null,
        value: null,
        picUrl: null

      },
      fileList: [],
      dialogVisible: false,
      disabled: false,
      dialogImageUrl: '',
      inputVisible: false,
      inputValue: '',
      keywords: [],
      categoryList: [],
      value: [],
      refresh: 0,
      isClear: false,
      editorOption: quillConfig,
      specificationTableData: [],
      productListTableData: [],
      attributeListTableData: [],

      // 商品规格弹框变量
      specificationdialogFormVisible: false,
      formLabelWidth: '120px',
      checkSpecificationFileFlag: null,
      specificationLoading: false,
      specificationAddRules: {
        specification: [{ required: true, message: '请填写规格名称', trigger: 'blur' }],
        value: [{ required: true, message: '请填写规格值', trigger: 'blur' }]
      },
      // 商品参数弹框变量
      attribute: {
        attribute: null,
        value: null
      },
      attributedialogFormVisible: false,
      attributeLoading: false,
      attributeAddRules: {
        attribute: [{ required: true, message: '请填写参数名称', trigger: 'blur' }],
        value: [{ required: true, message: '请填写参数值', trigger: 'blur' }]
      },
      // 商品库存设置弹框变量
      specificationsdialogFormVisible: false,
      specificationsEditRules: {
        specifications: [{ required: true, message: '请填写货品规格', trigger: 'blur' }],
        number: [{ required: true, message: '请填写货品数量', trigger: 'blur' }],
        price: [{ required: true, message: '请填写货品价格/元', trigger: 'blur' }, { pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: '请输入正确的价格,可保留两位小数' }]
      },
      editSpecifications: {
        specifications: null,
        number: null,
        price: null,
        url: null
      },
      // 整体页面的表单验证
      productFormRules: {
        name: [{ required: true, message: '请填写商品名称', trigger: 'blur' }],
        counterPrice: [{ required: true, message: '请填写商品专柜价格', trigger: 'blur' }, { pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: '请输入正确的价格,可保留两位小数' }],
        retailPrice: [{ required: true, message: '请填写商品当前价格', trigger: 'blur' }, { pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: '请输入正确的价格,可保留两位小数' }],
        unit: [{ required: true, message: '请填写商品单位', trigger: 'blur' }]
      }

    }
  },
  computed: {
    ...mapGetters(['fileUpload', 'token'])
  },
  created() {
    this.queryShopGoods()
    window.scrollTo(0, 0)
  },

  methods: {
    queryShopGoods() {
      queryShopGoodsByid({ goodId: parseInt(this.$route.query.id) }).then((result) => {
        this.edit = result.data.goods

        // 富文本编辑器神坑处理
        this.$nextTick(function() {
          this.$refs.myTextEditor.quill.enable(false)
          this.$refs.myTextEditor.quill.blur()
        })

        this.$refs.myTextEditor.quill.enable(false) // 刚开始时，不聚焦
        setTimeout(() => {
          this.$refs.myTextEditor.quill.enable(true) // 2秒之后可以点击（聚焦）
        }, 2000)
        this.edit.counterPrice = this.edit.counterPrice / 100
        this.edit.retailPrice = this.edit.retailPrice / 100
        this.fileList = []
        result.data.goods.gallery.split(',').forEach(element => {
          this.fileList.push({

            url: element.replace('[', '').replace(']', '').replace('"', '')

          })
        })

        this.keywords = []
        this.keywords = result.data.goods.keywords.split(',')
        // 商品规格
        this.specificationTableData = result.data.specificationList
        // 商品库存
        this.productListTableData = result.data.productList
        // 商品参数
        this.attributeListTableData = result.data.attributeList
      }).catch((err) => {
        this.$message.error(err.msg)
      })
      this.value = []
      // 查询类目
      queryShopCategoryList({ name: null }).then(response => {
        const data = response.data
        data.forEach(element => {
          if (element.children != null && element.children.length > 0) {
            const children = []
            element.children.forEach(chi => {
              if (chi.id === this.edit.categoryId) {
                this.value.push(element.id, chi.id)
              }
              children.push({
                label: chi.name,
                value: chi.id
              })
            })
            this.refresh = this.refresh + 1
            this.categoryList.push({
              label: element.name,
              value: element.id,
              children: children
            })
          }
        })
      })
    },
    onSuccessImgUrl(file) {
      this.$message.success(file.msg)
      this.edit.picUrl = file.data
    },
    handleRemove(file) {
      for (var i = 0; i < this.fileList.length; i++) {
        // 这里存在两种情况
        // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
        //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
        // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
        var url
        if (file.response === undefined) {
          url = file.url
        } else {
          url = file.response.data.url
        }

        if (this.fileList[i].url === url) {
          this.fileList.splice(i, 1)
        }
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleDownload(file) {
    },
    onSuccess(file) {
      this.$message.success(file.msg)
      this.fileList.push({ uid: Math.round(Math.random() * 5), url: file.data })
    },
    uploadError(file) {

    },
    handleClose(tag) {
      this.keywords.splice(this.keywords.indexOf(tag), 1)
    },

    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.keywords.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    change(val) {
    //   console.log(val)
    },
    handleSpecificationShow() {

    },
    // 商品规格弹框
    addSpecificationdialog() {
      this.specificationdialogFormVisible = true
    },
    specificationdialogClose() {
      this.specificationdialogFormVisible = false
      this.specification.picUrl = null
      this.specification.specification = null
      this.specification.value = null
      this.$refs.specificationUpload.clearFiles()
    },
    specificationdialogSubmit(formName) {
      this.$refs[formName].validate((valida) => {
        if (valida) {
          this.specificationLoading = true
          this.$refs.specificationUpload.submit()

          setTimeout(() => {
            this.specificationTableData.push({
              picUrl: this.checkSpecificationFileFlag,
              specification: this.specification.specification,
              value: this.specification.value
            })

            this.specificationdialogFormVisible = false
            this.specification.picUrl = null
            this.specification.specification = null
            this.specification.value = null
            this.checkSpecificationFileFlag = null
            this.$refs.specificationUpload.clearFiles()
            this.specificationLoading = false
            this.specToProduct()
          }, 1500)
          // this.specificationdialogClose()
        } else {
          return false
        }
      })
    },
    onSuccessSpecificationImg(file) {
      this.checkSpecificationFileFlag = file.data
    },
    checkSpecificationFile(file) {
      if (file != null) {
        //
      } else {
        this.$refs.specificationUpload.abort()
      }
    },
    removeSpecification(row) {
      const index = this.specificationTableData.findIndex(item => item.value === row.value)
      this.specificationTableData.splice(index, 1)
    },
    // 商品参数
    handleAttributeShow() {
      this.attributedialogFormVisible = true
    },
    attributedialogClose() {
      this.attributedialogFormVisible = false
      this.attribute.attribute = null
      this.attribute.value = null
    },
    attributedialogSubmit(formName) {
      this.$refs[formName].validate((valida) => {
        if (valida) {
          this.attributeListTableData.push({
            attribute: this.attribute.attribute,
            value: this.attribute.value
          })

          this.attributedialogClose()
        } else {
          return false
        }
      })
    },
    specificationsdialogClose() {
      // this.editSpecifications = null
      this.specificationsdialogFormVisible = false
      this.editSpecifications.number = null
      this.editSpecifications.specifications = null
      this.editSpecifications.url = null
      this.editSpecifications.id = null
      this.editSpecifications.price = null
      this.$refs.editSpecificationsUpload.clearFiles()
    },
    specificationsdialogSubmit(formName) {
      this.$refs[formName].validate((valida) => {
        if (valida) {
          console.log(this.editSpecifications)
          // this.productListTableData.push(this.editSpecifications)
          const index = this.productListTableData.findIndex(item => item.id === this.editSpecifications.id)
          this.productListTableData.splice(index, 1, {
            id: this.editSpecifications.id,
            specifications: this.editSpecifications.specifications,
            number: this.editSpecifications.number,
            url: this.editSpecifications.url,
            price: this.editSpecifications.price * 100

          })
          this.specificationsdialogClose()
        } else {
          return false
        }
      })
    },
    removeAttribute(row) {
      const index = this.attributeListTableData.findIndex(item => item.attribute === row.attribute)
      this.attributeListTableData.splice(index, 1)
      // this.attributeListTableData.forEach(itme => {
      //   if (itme.attribute === row.attribute) {
      //     this.attributeListTableData.splice(itme, 1)
      //     return
      //   }
      // })
    },
    // 动态生成规格商品库存列表
    specToProduct() {
      if (this.specificationTableData.length === 0) {
        return
      }
      // 根据specifications创建临时规格列表
      var specValues = []
      var spec = this.specificationTableData[0].specification
      var values = []
      values.push(0)

      for (var i = 1; i < this.specificationTableData.length; i++) {
        const aspec = this.specificationTableData[i].specification

        if (aspec === spec) {
          values.push(i)
        } else {
          specValues.push(values)
          spec = aspec
          values = []
          values.push(i)
        }
      }
      specValues.push(values)

      // 根据临时规格列表生产货品规格
      var productsIndex = 0
      var products = []
      var combination = []
      var n = specValues.length
      for (var s = 0; s < n; s++) {
        combination[s] = 0
      }
      var index = 0
      var isContinue = false
      do {
        var specifications = []
        for (var x = 0; x < n; x++) {
          var z = specValues[x][combination[x]]
          specifications.push(this.specificationTableData[z].value)
        }
        products[productsIndex] = {
          id: productsIndex,
          specifications: specifications,
          price: 0.0,
          number: 0,
          url: ''
        }
        productsIndex++

        index++
        combination[n - 1] = index
        for (var j = n - 1; j >= 0; j--) {
          if (combination[j] >= specValues[j].length) {
            combination[j] = 0
            index = 0
            if (j - 1 >= 0) {
              combination[j - 1] = combination[j - 1] + 1
            }
          }
        }
        isContinue = false
        for (var p = 0; p < n; p++) {
          if (combination[p] !== 0) {
            isContinue = true
          }
        }
      } while (isContinue)

      this.productListTableData = products
    },
    specificationsdialogShow(row) {
      this.specificationsdialogFormVisible = true
      this.editSpecifications.number = row.number
      this.editSpecifications.specifications = this.stringReplace(row.specifications)
      this.editSpecifications.url = row.url
      this.editSpecifications.id = row.id
      this.editSpecifications.price = this.amount(row.price)
    },

    stringReplace(val) {
      if (val === null) {
        return null
      }
      return val.toString().replace('[', '').replace(']', '').replace('"', '').replace('"', '')
    },
    amount(val) {
      return (val / 100).toFixed(2)
    },
    editSpecificationsImgSuccess(file) {
      this.$message.success(file.msg)
      this.editSpecifications.url = file.data
    },
    pruductSubmit(formName) {
      this.$refs[formName].validate((valida) => {
        if (valida) {
          this.edit.keywords = this.keywords.join(',')
          const queryPage = { specification: this.specificationTableData, inventory: this.productListTableData, productAttribate: this.attributeListTableData }
          var data = Object.assign(queryPage, this.edit)
          this.loading = true
          updateProduct(data).then(response => {
            this.$notify({ title: response.msg, duration: 1000, type: 'success' })
            setTimeout(() => {
              this.loading = false
            }, 1000)
            this.$router.push({ path: '/goods/comm/list' })
          })
        } else {
          return false
        }
      })
    },
    oncancle() {
      this.$router.push({ path: '/goods/comm/list' })
    }
  }
}

</script>
<style>
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }
  .avatar {
    width: 148px;
    height: 148px;
    display: block;
  }
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

</style>
